package leetcode.editor.cn;

import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;

/**
题目名字---:两个数组的交集 II
题目编号---:350	
解题时间---:2021-10-18 21:27:20
*/

public class IntersectionOfTwoArraysIi{
    public static void main(String[] args) {
        Solution solution = new IntersectionOfTwoArraysIi().new Solution();    
    }
    
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length>nums2.length) {
            return intersect(nums2,nums1);
        }
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
             int count = hashMap.getOrDefault(nums1[i],0)+ 1;
             hashMap.put(nums1[i],count);
        }
        int[] result = new int[nums1.length];
        int index=0;
        for (int num : nums2) {
            Integer orDefault = hashMap.getOrDefault(num, 0);
            if (orDefault>0) {
                result[index++] = num;
                orDefault--;
                if (orDefault>0) {
                    hashMap.put(num,orDefault);
                }else {
                    hashMap.remove(num);
                }
            }
        }
        return Arrays.copyOfRange(result, 0, index);
    }

}
//leetcode submit region end(Prohibit modification and deletion)

}